//
//  one.m
//  享动
//
//  Created by lanou on 16/4/14.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "one.h"
#import "AppDelegate.h"
#import "MusicDetailTableViewCell.h"
#import "musicRunModel.h"
#import "Entity.h"
#import "musicChooseCell.h"
#import "MusicPlayViewController.h"
#import "RequestManager.h"
#import "musicRunModel.h"
#import <MJRefresh.h>
@interface one ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray * modelArray;

@property(nonatomic,strong)NSManagedObjectContext * context;


@property(nonatomic,strong)NSString * whichCell;

@property(nonatomic,assign)NSInteger startIndex;

@property(nonatomic,strong)NSMutableArray * anotherArr;

@property(nonatomic,assign)NSInteger a;

@property(nonatomic,strong)NSMutableArray * backArray;

@end

@implementation one

+ (one *)shareInstence
{
   
        static one * vc = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            vc = [[one alloc]init];
        });
        return vc;
   
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _anotherArr = [NSMutableArray array];
    _modelArray = [NSMutableArray array];
    _backArray = [NSMutableArray array];
    
    if ([_identifierOne isEqualToString:@"noChoose"]) {
        self.tableView.rowHeight = 70;
    }
    else
    {
         self.tableView.rowHeight = 40;
    }
    
    self.navigationItem.title = @"收藏";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.tableView registerClass:[MusicDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.tableView registerClass:[musicChooseCell class] forCellReuseIdentifier:@"cells"];

 
    [self get];

    
    
    
}
- (void)get
{
    AppDelegate * delegate = [UIApplication sharedApplication].delegate;
    
    _context = delegate.managedObjectContext;
    _modelArray = [NSMutableArray array];
    
    NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    
    NSPredicate * cate = [NSPredicate predicateWithFormat:@"isCollection= '1'"];
    
    [request setPredicate:cate];
    
    NSArray * array = [_context executeFetchRequest:request error:nil];
    
    if (array.count != 0) {
        
        
        for (Entity * c  in array) {
            musicRunModel * model = [[musicRunModel alloc]init];
            model.name =  c.name ;
            model.albumUrl = c.albumUrl ;
            model.author =  c.author ;
            model.introduce = c.introduce ;
            model.url = c.url  ;
            model.bpm = [c.bpm integerValue];
            model.isCollection = YES;
         
            model.tableName = _tableName;
            [_modelArray addObject:model];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
        }
    }
    else
    {
        NSLog(@"没有");
    }

}
- (void)viewWillAppear:(BOOL)animated
{
    [self get];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    musicChooseCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    musicRunModel *model = _modelArray[indexPath.row];
    
     if ([_identifierOne isEqualToString:@"noChoose"]) {
         
         for (MusicDetailTableViewCell * cell in self.tableView.visibleCells) {
             cell.chooseView.hidden = YES;
         }
         for (musicRunModel *model in self.modelArray) {
             model.isChoose = NO;
         }
         
         
         
         MusicPlayViewController * play = [[MusicPlayViewController alloc]initWithNibName:@"musicPlay" bundle:[NSBundle mainBundle]];
         musicRunModel * model = self.modelArray[indexPath.row];
         
         play.model = model;
         
         play.modelArray = _modelArray;
         
         play.index = indexPath.row;
         
         // -------------------------------- 显示谁被选中的歌曲
         model.isChoose = YES;
         
         MusicDetailTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
         
         cell.chooseView.hidden = NO;
         
         
         [self presentViewController:play animated:YES completion:nil];

     }
     else{
         
    
  
    
    if (model.isSelect) {
        [_backArray removeObject: model];
        [cell.chooseButton setImage:[UIImage imageNamed:@"noChoose"] forState:UIControlStateNormal];
    }
    else
    {
        [_backArray addObject:model];
        [cell.chooseButton setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
    }
    
    model.isSelect = !model.isSelect;
    
    // block 传值
    NSInteger count = 0;
    for (musicRunModel * model in _modelArray) {
        if (model.isSelect == YES) {
            count ++;
        }
    }
    
    _a = count;
    
    if (self.BlockC != nil) {
        self.BlockC(_a,_backArray);
    }
}
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    
    NSLog(@"-------------------------%@",_identifierOne);
    

    musicRunModel * model = _modelArray[indexPath.row];
    
    if ([_identifierOne isEqualToString:@"noChoose"]) {
        
    MusicDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
        if (model.isCollection) {
           
        [cell.moreButton  setBackgroundImage:[UIImage imageNamed:@"fillstar"] forState:UIControlStateNormal];
           
        }
        [cell.moreButton addTarget:self action:@selector(more:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell cellFormodel:model];
        
        
        cell.selectionStyle  = UITableViewCellSelectionStyleNone;
        
        
        if (model.isChoose) {
            
            cell.chooseView.hidden = NO;
        }
        else
        {
            cell.chooseView.hidden = YES;
        }
        

        return cell;
        
        


    }
    else
    {
    musicChooseCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cells" forIndexPath:indexPath];
        
    cell.numberLabel.text = [NSString stringWithFormat:@"%02ld .",indexPath.row+1];
    musicRunModel * model = _modelArray[indexPath.row];
    
    cell.nameLabel.text = model.name;
    

    if (model.isSelect) {
        [cell.chooseButton setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.chooseButton setImage:[UIImage imageNamed:@"noChoose"] forState:UIControlStateNormal];
      }
        
        return cell;

    }
    
}




- (void)more:(UIButton * )button
{
    
    
    MusicDetailTableViewCell * cell = (MusicDetailTableViewCell *)button.superview.superview;
    
    NSIndexPath * indexpath = [self.tableView indexPathForCell:cell];
    
    musicRunModel * model = _modelArray[indexpath.row];
    
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"确定取消收藏？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
            
            NSPredicate * cate = [NSPredicate predicateWithFormat:@"isCollection= '1'"];
            
            [request setPredicate:cate];
            
            
            // 点击按钮的时候 搜索数据库 isCollection
            // 判断是否存在 同样的model  存在就不添加  并且删除
            
            NSArray * array = [_context executeFetchRequest:request error:nil];
            
            for (Entity * c  in array) {
                if ([c.name isEqualToString:model.name]) {
                    [_modelArray removeObject:model];
                    [_context deleteObject:c];
                    [_context save:nil];
                    [self.tableView reloadData];

                }
                
            }

        }];
        UIAlertAction * cancel1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:cancel];
        [alert addAction:cancel1];
        cancel.enabled = YES;
        cancel1.enabled = YES;
        [self presentViewController:alert animated:YES completion:^{
          
        }];
        
    });
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
